package com.travelDevelop.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.travelDevelop.commons.bean.User;
import com.travelDevelop.commons.util.CryptTool;
import com.travelDevelop.commons.util.WebConst;
import com.travelDevelop.service.LoginCheckService;
import com.travelDevelop.service.UserService;





@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	UserService userService;
	
	String a;

	@RequestMapping("")
	public String index(HttpServletRequest request,HttpServletResponse response,RedirectAttributes attr) {
		// 已经登录的跳转到 index 首页
		String str = request.getParameter("loginInfo");
		if (str != null && !str.isEmpty()) {
			a=str;
		} else {
			request.setAttribute("loginInfo", a);
			a=null;
		}
		
		HttpSession session = request.getSession();
		if(session.getAttribute(WebConst.SESSION_LOGIN_USER)!=null){
			return "redirect:/";
		}
		response.setHeader("sessionstatus", "timeout");
		return "index";
	}
	

	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request,RedirectAttributes attr,HttpServletResponse response) throws Exception {
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		Map<String, Object> responseMap = new HashMap<>();
		Integer sum =  (Integer)session.getAttribute("isCheck");
		if (sum != null && sum > 3) {
			String checkText = request.getParameter("check_text").toUpperCase();
			String sessionCheckText = (String) session.getAttribute("checkText");
			responseMap.put("isCheck", 4);
			//验证码判断
			if (sessionCheckText == null) {
				responseMap.put("loginInfo", "验证码过期！");
				return responseMap;
			}else if (!sessionCheckText.equals(checkText)) {
				//验证码不正确
				responseMap.put("loginInfo", "验证码错误！");
				return responseMap;
			}
			//request.setAttribute("isCheck", sum);
		}
		User user = null;
		// 对password进行MD5加密
		try{
			password = CryptTool.md5Digest(password).toUpperCase();
			user = userService.getUserByUsernameAndPwd(username, password);
		}catch (Exception e){
			e.printStackTrace();
		}
		// User user = userService.getUserByUsernameAndPwd(username, password);
		if(user==null){
			if (sum == null) {
				session.setAttribute("isCheck", 1);
			}else{
				Integer Isum = sum;
				session.setAttribute("isCheck",++Isum);
				responseMap.put("isCheck", Isum);
			}
			responseMap.put("loginInfo", "用户名或密码错误！");
			//attr.addAttribute("loginInfo", "用户名或密码错误！");
			responseMap.put("success", 0);
			//request.setAttribute("isCheck", sum);
			return responseMap;
		}
		session.setMaxInactiveInterval(30*60);
		session.setAttribute(WebConst.SESSION_LOGIN_USER, user);
		session.setAttribute(WebConst.SESSION_LOGIN_USER_ID, user.getId());
		session.setAttribute(WebConst.SESSION_LOGIN_USER_ROLE, user.getRole());
		responseMap.put("success", 1);
		
		return responseMap;
	}


	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.setAttribute(WebConst.SESSION_LOGIN_USER, null);

		return "redirect:/index";
	}
	
	
	/**
	 * 验证码
	 * @param request
	 * @throws Exception 
	 */
	@RequestMapping(value = "/VC", method = RequestMethod.GET)
	@ResponseBody
	public void  VC(HttpServletRequest request, HttpServletResponse response ) { 
		HttpSession session = request.getSession();
		LoginCheckService code=new LoginCheckService();
		BufferedImage image = code.getImage();
		session.setAttribute("checkText", code.getText());
		//session.setMaxInactiveInterval(60);
		try {
			ImageIO.write(image,"jpg",response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} 
	} 
	
	
	
	/**
	* 功能:提供给前端检验请求用户是否已经登录
	* @param :
	* @reuslt: 把map对象转成json对象返回前端，map中的token大于0则说明，请求用户已经登录
	* @throws:  
	* @author:redfly 
	*/
	@RequestMapping("/checkToken")
	@ResponseBody
	public Map<String, Integer> checkToken(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Map<String, Integer> responseMap = new HashMap<>();
		
		if(session.getAttribute(WebConst.SESSION_LOGIN_USER)!= null) {
			responseMap.put("token", 1);
		}else {
			responseMap.put("token", 0);
		}
		responseMap.put("isCheck",(Integer)session.getAttribute("isCheck"));
		return responseMap;
	}
	
	

	
}
